package model

import (
	"goods_rpc/database/mysql"
	"gorm.io/gorm"
	"strconv"
)

type Goods struct {
	gorm.Model
	GoodsImages  string  `gorm:"type:varchar(225);comment:商品图片;"`
	GoodsName    string  `gorm:"type:varchar(50);comment:商品名称;"`
	GoodsPrice   float64 `gorm:"type:decimal(10,2);comment:商品价格;"`
	GoodsStock   int64   `gorm:"type:int(11);comment:商品库存;"`
	GoodsSales   int64   `gorm:"type:int(11);comment:商品销量;"`
	GoodsStatus  int64   `gorm:"type:int(11);comment:商品状态;"`
	AuditsStatus int64   `gorm:"type:int(11);comment:审核状态;"`
	AuditsGroup  int64   `gorm:"type:int(11);comment:商品分组;"`
}

// 新增商品
func (g *Goods) CreateGoods() (*Goods, error) {
	return g, mysql.WitMysql(func(db *gorm.DB) error {
		return db.Create(g).Error
	})
}

// 获取商品列表
func (g *Goods) GetGoodsList(page, pageSize int) (*Goods, error) {
	return g, mysql.WitMysql(func(db *gorm.DB) error {
		return db.Where("goods_name like ?", "%"+g.GoodsName+"%").
			Or("goods_status = ?", strconv.Itoa(int(g.GoodsStatus))).
			Scopes(Paginate(page, pageSize)).Find(g).Error
	})
}

// 分页
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
